package org.linlinjava.litemall.wx.web;

import org.apache.ibatis.annotations.Param;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallHistory;
import org.linlinjava.litemall.db.domain.LitemallUserEr;
import org.linlinjava.litemall.db.service.GoodsHistoryService;
import org.linlinjava.litemall.db.service.LitemallUserErService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static org.linlinjava.litemall.wx.util.WxResponseCode.AUTH_INVALID_ACCOUNT;

@RestController
@RequestMapping("/wx/queryBalance")
@Validated
public class WxGoodsUserErController {

    @Autowired
    private LitemallUserErService userErService;

    @Autowired
    private GoodsHistoryService historyService;

    @PostMapping("userer")
    public Object change(@RequestBody String body, HttpServletRequest request){
        String username = JacksonUtil.parseString(body,"username");
        String balance = JacksonUtil.parseString(body,"balance");
        String goodsname = JacksonUtil.parseString(body,"goodsname");
        LitemallUserEr userEr = userErService.queryAllById(username);
        if(Integer.parseInt(balance) > Integer.parseInt(userEr.getBalance())){
            return ResponseUtil.fail(101,"余额不足");
        }
        HashMap map = new HashMap();
        map.put("username",username);
        map.put("balance",balance);
        map.put("goodsname",goodsname);
        if(userEr == null){
            return ResponseUtil.fail(AUTH_INVALID_ACCOUNT, "用户未注册");
        }else{
            int updateNum = userErService.updateUserErById(username, balance);
            LitemallUserEr litemallUserEr = userErService.queryAllById(username);
            int insertNum = historyService.insertHistory(map);
        }
        return ResponseUtil.ok("扣款成功");
    }

    @PostMapping("history")
    public Object queryHistory(@RequestBody String body){
        String s = JacksonUtil.parseString(body, "goodsname");
        List<LitemallHistory> allHistory = historyService.queryOne(s);
        for (LitemallHistory litemallHistory1 : allHistory) {
            System.out.println(litemallHistory1);
        }
        return ResponseUtil.okList(allHistory);
    }
}
